package client_commands;

import java.util.StringTokenizer;

import client.ClientApplication;
import client.ClientBindObject;
import client_gui_chat.ChatDialog;

public class CLIENT_SEND_MSGCommand extends Command {

	public CLIENT_SEND_MSGCommand(String parameter) {
		setCode(CLIENT_SEND_MSG);
		setParameter(parameter);
	}
	
	@Override
	public boolean executeCommand(ClientApplication theApp) {
		
		StringTokenizer tokens = new StringTokenizer(getParameter());
		
		StringBuffer messageBuffer = new StringBuffer();
		
		ClientBindObject cbo = ClientApplication.clientBinding.get(tokens.nextToken());
		
		while ( tokens.hasMoreTokens() ) {
			messageBuffer.append(tokens.nextToken());
			messageBuffer.append(" ");
		}
		
		
		if (cbo.getDialog() == null) {
			
			try {
				ClientApplication.dialogSemaphore.acquire();
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			if (cbo.getDialog() == null) {
				ChatDialog dialog = new ChatDialog(theApp.getWindow(), cbo.getUser());
				cbo.setChatDialog(dialog);
				cbo.setChatDialogConnection(cbo.getConnection());
				dialog.setVisible(true);
			}
			
			ClientApplication.dialogSemaphore.release();
		}
		
		cbo.getDialog().writeUserSaysMessage(cbo.getUser().getNickname() + " says:\n");
		cbo.getDialog().writeMessage(messageBuffer.toString().trim());
		
		return true;
	}
	
}
